package solution._0030._0031;

import static common.Utils.print;

/**
 * Created by chen_snow
 * Date: 2021/5/18 23:16
 * Description:
 */
public class Solution {
    public static void main(String[] args) {
        int datas[] = {1, 2, 3};

        nextPermutation(datas);
    }

    public static void nextPermutation(int[] nums) {
        int index = findIndex(nums);
        if (index == -1) {
            change(nums, 0, nums.length - 1);
            return;
        }

        findLargerAndSwap(nums, index);
        print(nums);
        change(nums, index + 1, nums.length - 1);
        print(nums);
    }

    /**
     * 根据index找到index后第一个比nums[index]大的数，并月index交换
     * @param nums
     * @param index
     */
    public static void findLargerAndSwap(int[] nums, int index) {
        for (int i = nums.length - 1; i > index; i--) {
            if (nums[i] > nums[index]) {
                swap(nums, i, index);
                return;
            }
        }
    }

    /**
     * 找到第一个后一位比前一位大的index
     * @param nums
     * @return
     */
    public static int findIndex(int[] nums) {
        if (nums.length < 2) {
            return -1;
        }

        int last = nums.length - 1;
        int secondLast = last - 1;

        while (secondLast >= 0) {
            if (nums[last] > nums[secondLast]) {
                return secondLast;
            }

            last = secondLast;
            secondLast--;
        }

        return -1;
    }

    public static void change(int[] nums, int start, int end) {
        while (start < end) {
            swap(nums, start, end);
            start++;
            end--;
        }
    }

    public static void swap(int[] nums, int start, int end) {
        int tmp = nums[start];
        nums[start] = nums[end];
        nums[end] = tmp;
    }


}
